namespace Pay.Core {
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text.RegularExpressions;

    public static class HtmlContentHelper {
        public static IEnumerable<string> GetHtmlImageUrlList(string htmlText) {
            MatchCollection matchs = new Regex("<img\\b[^<>]*?\\bsrc[\\s\\t\\r\\n]*=[\\s\\t\\r\\n]*[\"']?[\\s\\t\\r\\n]*(?<imgUrl>[^\\s\\t\\r\\n\"'<>]*)[^<>]*?/?[\\s\\t\\r\\n]*>", RegexOptions.IgnoreCase).Matches(htmlText);
            int num = 0;
            string[] strArray = new string[matchs.Count];
            foreach (Match match in matchs) {
                strArray[num++] = match.Groups["imgUrl"].Value;
            }
            return strArray;
        }

        public static string RemoveScriptsAndStyles(string htmlText) {
            htmlText = Regex.Replace(htmlText, @"<\s*script[^>]*?>.*?<\s*/\s*script\s*>", "", RegexOptions.IgnoreCase);
            htmlText = Regex.Replace(htmlText, @"<\s*style[^>]*?>.*?<\s*/\s*style\s*>", "", RegexOptions.IgnoreCase);
            return htmlText;
        }
        public static string ReplaceHtmlTag(string html, int length = 0) {
            string strText = Regex.Replace(html, "<[^>]+>", "");
            strText = Regex.Replace(strText, "&[^;]+;", "");

            if (length > 0 && strText.Length > length)
                return strText.Substring(0, length);

            return strText;
        }
        public static string TransferToLocalImage(string htmlText, string relativeRootPath, string desDir, string imgSrcPreText = "") {
            if (!relativeRootPath.EndsWith("/")) {
                relativeRootPath = relativeRootPath + "/";
            }
            if (!Directory.Exists(desDir)) {
                Directory.CreateDirectory(desDir);
            }
            int num = 0;
            List<string> list2 = GetHtmlImageUrlList(htmlText).ToList<string>().FindAll(imgurl => !imgurl.StartsWith("data:"));
            WebClient client = new WebClient();
            foreach (string str4 in list2) {
                string[] strArray = str4.Split(new char[] { '.' });
                string str3 = strArray[strArray.Length - 1];
                string str = Guid.NewGuid().ToString("N") + "." + str3;
                string fileName = desDir + "/" + str;
                try {
                    if (str4.StartsWith("http://")) {
                        client.DownloadFile(str4, fileName);
                    } else {
                        System.IO.File.Copy(relativeRootPath + str4, fileName, true);
                    }
                    htmlText = htmlText.Replace(str4, imgSrcPreText + str);
                } catch {
                }
                num++;
            }
            htmlText = htmlText.Replace("<IMG", "<img").Replace("</IMG", "</img");
            return htmlText;
        }
    }
}

